import axios from 'axios';
import { useUserStore } from '@/store/settings.js';
import { ElMessage } from 'element-plus';
import router from '@/router';

const axiosInstance = axios.create({
  baseURL: 'http://localhost:8080/api',
  timeout: 1000 * 60 * 60 * 12, // 12小时超时
});

// 请求拦截器
axiosInstance.interceptors.request.use(
  (config) => {
    const userStore = useUserStore();
    const token = userStore.getUser.token;

    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`; // 添加 Token
    }

    return config;
  },
  (error) => {
    console.error('请求错误:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
axiosInstance.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response && error.response.status === 401) {
      ElMessage.error('登录已过期，请重新登录');
      const userStore = useUserStore();
      userStore.delUser(); // 清除用户信息
      router.push({ name: 'LoginX' }); // 跳转到登录页面
    } else if (error.response && error.response.status === 500) {
      ElMessage.error('服务器错误，请稍后再试');
    } else {
      ElMessage.error(error.message || '请求失败');
    }
    return Promise.reject(error);
  }
);

export default axiosInstance;
